package org.openfans.web;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.openfans.domain.Facade;
import org.openfans.domain.Auth;
import org.openfans.util.EncryptUtil;
import org.openfans.util.WebUtil;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.BaseCommandController;

public class LoginController extends BaseCommandController {
	private Facade facade;

	public void setFacade(Facade facade) {
		this.facade = facade;
	}

	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		WebUtil.letNoCache(response);
		String email = request.getParameter("email");
		String passwd = request.getParameter("passwd");

		if (email != null && passwd != null && !"".equals(email)
				&& !"".equals(passwd)) {
			Auth auth = new Auth();
			auth.setEmail(email);
			auth.setPasswd(passwd);
			try {
				auth = facade.authenticate(auth);
			} catch (Exception e) {
				// 记录下来，并忽略异常
				e.printStackTrace();
				auth = null;
			}

			if (null == auth) {
				response.getWriter().print("preFans");
				return null;
			}
			request.getSession().setAttribute("loginFans", auth.getFans());

			Cookie cookie = new Cookie("login", EncryptUtil.bind(String
					.valueOf(auth.getAuthId()), auth.getPasswd()));
			cookie.setMaxAge(60 * 60 * 24 * 90); // 保存90天

			response.addCookie(cookie);

			response.getWriter().print(auth.getFans().getNickName());
			return null;
		} else {// 登陆为访客
			response.getWriter().print("preFans");
			return null;
		}
	}
}
